package com.cskaoyan.config;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @description：
 * @author: 曹旭
 * @date: 2022/5/11 06:28
 */
@Data
@ConfigurationProperties(prefix = "aliyun")
@Component
public class AliyunComponent {
    String accessKeyId;
    String accessKeySecret;
    Oss oss;
    Sms sms;

    public OSSClient getOssClient() {
        OSSClient ossClient = new OSSClient(oss.getEndPoint(), accessKeyId, accessKeySecret);
        return ossClient;
    }

    public PutObjectResult fileUpload(String fileName, File file) {
        OSSClient ossClient = getOssClient();
        PutObjectResult putObjectResult = ossClient.putObject(oss.getBucket(), fileName, file);
        return putObjectResult;
    }

    public String fileUpload(String fileName, InputStream inputStream) {
        OSSClient ossClient = getOssClient();
        PutObjectResult putObjectResult = ossClient.putObject(oss.getBucket(), fileName, inputStream);

        String result = "https://"+oss.getBucket()+"."+oss.getEndPoint()+"/"+fileName;
        return result;
    }

    public String fileUpload(MultipartFile file) throws IOException {
        String fileName = UUID.randomUUID().toString().replaceAll("-","") + ".png";
        String url = fileUpload(fileName, file.getInputStream());
        return url;
    }

    public void sendMsg(String phoneNumber,String code){
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest commonRequest = new CommonRequest();
        commonRequest.setMethod(MethodType.POST);
        commonRequest.setDomain("dysmsapi.aliyuncs.com");
        commonRequest.setVersion("2017-05-25");
        commonRequest.setAction("SendSms");
        commonRequest.putQueryParameter("RegionId","cn-hangzhou");

        try {
            CommonResponse response = client.getCommonResponse(commonRequest);
            System.out.println(response.getData());
        } catch (ClientException e) {
            e.printStackTrace();
        }

    }
}
